import React, {Component} from 'react';
import {Form, Input, Select, Button, Row, Col, Avatar, Divider} from 'antd';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom'
import 'antd/dist/antd.css';
import '../../style/RegistrationEditor.css';

import * as actions from '../../action/index';
import {FormattedMessage} from "react-intl";

const FormItem = Form.Item;
const Option = Select.Option;
const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 6},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 14},
    },
};

const tailFormItemLayout = {
    wrapperCol: {
        xs: {
            span: 24,
            offset: 0,
        },
        sm: {
            span: 14,
            offset: 6,
        },
    },
};
const MAINLAND_PHONE_REG = /^1(3|4|5|7|8|9)\d{9}$/;
const HONGKANG_PHONE_REG = /^([5|6|8|9])\d{7}$/

class Registration extends Component {

    state = {
        confirmDirty: false,
        autoCompleteResult: [],
        areaCode: 86
    };

    parseUrl(url) {
        if (url === '') {
            return {}
        }
        let result = {};
        let query = url.split("?")[1];
        let queryArr = query.split("&");
        queryArr.forEach((item) => {
            let value = item.split("=")[1];
            let key = item.split("=")[0];
            result[key] = value;
        });
        return result;
    }

    componentDidMount() {
        this.props.getSocialInfo()
    }

    handleSubmit = (e) => {
        const urlParams = this.parseUrl(this.props.location.search)
        const {areaCode} = this.state
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                (async () => {
                    await this.props.register({...values, ...urlParams, areaCode});
                })();
            }

        });
    };

    handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({confirmDirty: this.state.confirmDirty || !!value});
    };

    checkPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('Two passwords that you enter is inconsistent!');
        } else {
            callback();
        }
    };

    checkConfirm = (rule, value, callback) => {
        const form = this.props.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], {force: true});
        }
        callback();
    };

    handleAreaCodeChange = (areaCode) => {
        this.setState({areaCode})
    }
    isHongKang = () => {
        return this.state.areaCode === '852'
    }
    checkMobilePhone = (rule, value, callback) => {
        if (this.isHongKang()) {
            return HONGKANG_PHONE_REG.test(value) ? callback() : callback(true);
        }
        return MAINLAND_PHONE_REG.test(value) ? callback() : callback(true);

}
    render() {
        const {getFieldDecorator} = this.props.form
        const {socialInfo} = this.props
        const isSocialRegister = !!socialInfo.nickname
        const prefixSelector = getFieldDecorator('prefix', {
            initialValue: '86',
        })(
            <Select style={{width: 80}} onChange={this.handleAreaCodeChange}>
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
                <Option value="852">+852</Option>
            </Select>
        );

        return (

            <div id="register">
                <Row>
                    <Col span={18} offset={3} className='register-position'>
                        <div className="register"><FormattedMessage id='注册'/></div>
                    </Col>
                </Row>
                {
                    isSocialRegister ?
                        <Row>
                            <Col className='register-social-info'>
                                <Avatar src={socialInfo.headImg}/>
                            </Col>
                            <Divider>{socialInfo.nickname} <FormattedMessage id='绑定新用户'/></Divider>
                        </Row>
                        :
                        ''
                }
                <Form onSubmit={this.handleSubmit} className="registration-editor-form">
                    <FormItem
                        {...formItemLayout}
                        label={(<span><FormattedMessage id='用户名'/></span>)}
                        hasFeedback

                    >
                        {getFieldDecorator('username', {
                            rules: [{
                                required: true,
                                message: <FormattedMessage id='用户名中只能包含文字、字母、数字、下划线等'/>,
                                validator: (rule, value, callback) => {
                                    const reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
                                    return reg.test(value) ? callback() : callback(true);
                                },
                                whitespace: true
                            }],
                        })(<Input/>)}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={(<span><FormattedMessage id='邮箱'/></span>)}
                        hasFeedback
                    >
                        {getFieldDecorator('email', {
                            rules: [{
                                type: 'email', message: 'The input is not valid E-mail!',
                            }, {
                                required: true, message: 'Please input your E-mail!',
                            }],
                        })(
                            <Input/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={(<span><FormattedMessage id='密码'/></span>)}
                        hasFeedback
                    >
                        {getFieldDecorator('password', {
                            rules: [{
                                required: true, message: 'Please input your password!',
                            }, {
                                validator: this.checkConfirm,
                            }],
                        })(
                            <Input type="password"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={(<span><FormattedMessage id='确认密码'/></span>)}
                        hasFeedback
                    >
                        {getFieldDecorator('confirm', {
                            rules: [{
                                required: true, message: 'Please confirm your password!',
                            }, {
                                validator: this.checkPassword,
                            }],
                        })(
                            <Input type="password" onBlur={this.handleConfirmBlur}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={(<span><FormattedMessage id='电话号码'/></span>)}
                    >
                        {getFieldDecorator('mobilePhone', {
                            rules: [{
                                required: true,
                                message: 'Incorrect format of mobile phone number.',
                                validator: this.checkMobilePhone,
                                whitespace: true
                            }],
                        })(
                            <Input addonBefore={prefixSelector} style={{width: '100%'}} type='number'/>
                        )}
                    </FormItem>

                    <FormItem {...tailFormItemLayout}>
                        <Row>
                            <Col span={10} offset={7}>
                                <Button type="primary" size='large' className='register-button'
                                        htmlType="submit"><FormattedMessage id='注册'/></Button>
                            </Col>
                        </Row>
                    </FormItem>

                </Form>
                <Row>
                    <Col span={12} offset={9} className='login-position'>
                        <div className=""><FormattedMessage id='若已有账户，点击此处'/>
                            <a href={`${process.env.REACT_APP_CAS_LOGIN_URL}`}><FormattedMessage id='登录'/></a></div>
                    </Col>
                </Row>
            </div>
        );
    }
}


const RegistrationForm = Form.create()(Registration);
const mapStateToProps = state => ({registerInfo: state.registerInfo, socialInfo: state.socialInfo});
const mapDispatchToProps = dispatch => ({
    register: values => dispatch(actions.createUser(values)),
    getSocialInfo: () => dispatch(actions.getSocialInfo())
});

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(RegistrationForm));
